#pragma once
#include <iostream>
#include <string>
#include <pthread.h>
#include <cassert>
#include <functional>
using namespace std;

//声明
class Thread;
//创建一个类，专门保存上下文
struct context
{
    Thread* _this;
    void* _args;
};

class Thread
{
public:
    typedef function<void*(void*)> func;//包装器
    Thread(func fc,void* args = nullptr,int number = 0)   
    :_fc(fc)
    ,_args(args) 
    {
        char buffer[128];
        snprintf(buffer,sizeof buffer,"thread: %d",number);
        _name = buffer;
        //创建线程
        context* ct = new context();
        ct->_this = this;
        ct->_args = _args;
        int n = pthread_create(&tid,nullptr,start_routine,ct);
        assert(0 == n);
        (void)n;//防止报warning

    }
    //这里不能使用this，所以设计成静态
    static void* start_routine(void* args)
    {
        context* ct = static_cast<context*>(args);
        void* ret = ct->_this->run(ct->_args);
        delete ct;
        return ct;
    }
    void* run(void* args)
    {
        return _fc(args);
    }
    void join()
    {
        int n = pthread_join(tid,nullptr);
        assert(0 == n);
        (void)n;
    }
private:
    string _name;
    func _fc;
    void* _args;
    pthread_t tid;
};